import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Test11_16 {

    public  volatile  String  code="A";
    public  volatile  int num=1;

    public  void printJi(){
        synchronized (this){
            while (!code.equals("A")){
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName()+num++);
            code="B";
            notifyAll();
        }
    }


    public  void printOu(){
        synchronized (this){
            while (!code.equals("B")){
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName()+num++);
            code="A";
            notifyAll();
        }
    }


    public  volatile  String  CODE="A";
    public  volatile  int count=1;


    ReentrantLock lock=new ReentrantLock();
    Condition A=lock.newCondition();
    Condition B=lock.newCondition();

    public  void printJi1(){
        lock.lock();
        try {
            while (!CODE.equals("A")){
                //TODO:2023/10/17 根据代码的提示把try  catch 写在了这个位置
            A.await();
            }
            System.out.println(Thread.currentThread().getName()+count);
            count++;
            CODE="B";
            B.signalAll();
        }catch (InterruptedException  e){
            //TODO:2023/10/17 容易犯的错误
//            System.out.println(e.printStackTrace());
            e.printStackTrace();
        }finally {
            lock.unlock();
        }


        //TODO:2023/11/16  面试现场临时发挥写的
//        while (!lock.tryLock()) {
//            try {
//                A.await();
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        }
//        lock.lock();
//        System.out.println(Thread.currentThread().getName()+num++);
//        B.signalAll();
//        lock.unlock();
    }

    public  void printOu1(){
    while (!lock.tryLock()) {
       try {
           B.await();
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
    }
        lock.lock();
        System.out.println(Thread.currentThread().getName()+num++);
        A.signalAll();
        lock.unlock();
    }





    public static void main(String[] args) {
        Test11_16 test11_16 = new Test11_16();
        new Thread(()->{
            while (true){
                test11_16.printJi1();
            }

        },"线程A").start();
        new Thread(()->{
            while (true){
                test11_16.printOu1();
            }
        } ,"线程B").start();

    }


}
